package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.subway.rca.entity.SwCkClearDailyTicketReport;
import com.zdkj.subway.rca.entity.SwCkClearSouvenirTicketReport;
import com.zdkj.subway.rca.mapper.SwCkClearDailyTicketReportMapper;
import com.zdkj.subway.rca.mapper.SwCkClearSouvenirTicketReportMapper;
import com.zdkj.subway.rca.service.SwCkClearSouvenirTicketReportService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lu
 * @Date 2021-08-11
 */
@Service
public class SwCkClearSouvenirTicketReportServiceImpl extends ServiceImpl<SwCkClearSouvenirTicketReportMapper,SwCkClearSouvenirTicketReport> implements SwCkClearSouvenirTicketReportService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkClearSouvenirTicketReportServiceImpl.class);
    @Resource
    SwCkClearDailyTicketReportMapper swCkClearDailyTicketReportMapper;
    @Override
    public List<SwCkClearDailyTicketReport> listSwCkClearDailyTicketReport(String startDate, String endDate, String operatorsName, String lineCode) {
        List<SwCkClearDailyTicketReport> list = swCkClearDailyTicketReportMapper.listSwCkClearDailyTicketReport(startDate,endDate,operatorsName,lineCode);
        List<SwCkClearDailyTicketReport> listNew = new ArrayList<>();

        String operators = null;
        for(SwCkClearDailyTicketReport obj : list){
            if(!obj.getOperators().equals(operators) && operators != null){
                //计算相同运营商的合计
                SwCkClearDailyTicketReport sum = getSum(operators, list);
                listNew.add(sum);
            }
            operators = obj.getOperators();
            listNew.add(obj);
        }
        if(list.size() > 0) { //最后一个运营商
            SwCkClearDailyTicketReport sum = getSum(operators, list);
            listNew.add(sum);
        }
        SwCkClearDailyTicketReport sumAll = getSum("合计", list);
        sumAll.setLineName("--");
        listNew.add(sumAll);
        return listNew;
    }

    private SwCkClearDailyTicketReport getSum(String operators, List<SwCkClearDailyTicketReport> list){
        SwCkClearDailyTicketReport sumSwCkClearDailyTicketReport = new SwCkClearDailyTicketReport();
        sumSwCkClearDailyTicketReport.setOperators(operators);
        if(!operators.equals("合计")){
            sumSwCkClearDailyTicketReport.setLineName("小计");
        }
        if(operators.equals("合计")){
            sumSwCkClearDailyTicketReport.setOperatorsname(operators);
        }
        BigDecimal saleIncomeSouvenir = new BigDecimal("0");
        BigDecimal clearAmountSouvenir = new BigDecimal("0");
        String clearScaleSouvenir = "0.0";
        BigDecimal clearMoneySouvenir = new BigDecimal("0");

        for(SwCkClearDailyTicketReport obj : list){
            if(operators.equals("合计") || operators.equals(obj.getOperators())){
                saleIncomeSouvenir = saleIncomeSouvenir.add(obj.getSaleIncomeSouvenir() == null ? new BigDecimal("0") : obj.getSaleIncomeSouvenir());
                clearAmountSouvenir = clearAmountSouvenir.add(obj.getClearAmountSouvenir() == null ? new BigDecimal("0") : obj.getClearAmountSouvenir());
                clearScaleSouvenir = new BigDecimal(clearScaleSouvenir).add(new BigDecimal(obj.getClearScaleSouvenir())).toString();
                clearMoneySouvenir = clearMoneySouvenir.add(obj.getClearMoneySouvenir());
            }
        }

        sumSwCkClearDailyTicketReport.setSaleIncomeSouvenir(saleIncomeSouvenir);
        sumSwCkClearDailyTicketReport.setClearAmountSouvenir(clearAmountSouvenir);
        sumSwCkClearDailyTicketReport.setClearScaleSouvenir(new BigDecimal(clearScaleSouvenir).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        sumSwCkClearDailyTicketReport.setClearMoneySouvenir(clearMoneySouvenir.setScale(2,BigDecimal.ROUND_HALF_UP));

        return sumSwCkClearDailyTicketReport;
    }


    /**
     * 导出
     * @param startDate
     * @param endDate
     * @param operators
     * @param lineCode
     * @param response
     */
    @Override
    public void export(String startDate, String endDate, String operators, String lineCode, HttpServletResponse response) {
        List<SwCkClearDailyTicketReport> records = listSwCkClearDailyTicketReport(startDate,endDate,operators,lineCode);
        InputStream excelTemplateIs = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("纪念票收入清分报表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量
            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/SwCkClearSouvenirTicketReportExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("纪念票收入清分报表").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", startDate);
            map.put("endTime", endDate);
            excelWriter.fill(map, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出纪念票收入清分报表异常");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}
